import datetime
import json
import random
from zhitang_web import config
from django.db.models import Q
from django.shortcuts import render,HttpResponse
import requests
from app import models

def index(request):
    return HttpResponse("hello")

def get_openid(request):
    # url一定要拼接，不可用传参方式
    jscode=request.GET.get('jscode')
    headurl=request.GET.get('headurl')
    url = config.URL + "?appid=" + config.APPID + "&secret=" + config.SECRET + "&js_code=" + jscode + "&grant_type=authorization_code"
    r = requests.get(url)
    openid = r.json()['openid']

    #查找用户表中是否有这个openID
    openID=models.Users.objects.filter(openID=openid)
    # 如果没有，随机生成6位数的用户号，初始密码为123456，存到Users表中
    if not openID:
        user=models.Users()
        has_uid=1
        while has_uid:
            uID=random.randint(10000,99999)
            has_uid=models.Users.objects.filter(uID=uID)
        user.uID=str(uID)
        user.openID=openid
        user.pwd=str(123456)
        user.uName="无名"+user.uID
        user.save()
    else:
        user=models.Users.objects.filter(openID=openid)[0]
    # 返回uID
    return HttpResponse(user.uID)
#事件发送
def insertLaunch(request):
    uID=request.POST['uID']
    if 'pre_launchID' in request.POST:
        pre_launchID=request.POST['pre_launchID']
        launchEvent=models.EventsLaunch.objects.get(id=pre_launchID)
        ttitle=request.POST['title']
        launchEvent.eName=ttitle
        launchEvent.save()

    # title=request.POST['title']
    # beginDate=request.POST['beginDate']
    user=models.Users.objects.get(uID=uID)
    # eLanchList=models.EventsLaunch.objects.filter(Q(uID__uID=uID)&Q(eName=title)&Q(began=beginDate))
    # if not eLanchList:
    eLanch=models.EventsLaunch()
    eLanch.uID=user
    eLanch.eName='1'
    # if 'title' in request.POST:
    #     eLanch.eName=request.POST['title']
    eLanch.began=datetime.datetime.now().strftime('%Y-%m-%d')
    eLanch.Send_at=datetime.datetime.now().strftime('%Y-%m-%d')
    eLanch.save()
    return HttpResponse(eLanch.id)

def getEvents(request):
    id=request.POST['id']
    Ename=request.POST['title']
    uID=request.POST['uID']
    user=models.Users.objects.get(uID=uID)
    Estartat = request.POST['beginDate']
    EstartTime = request.POST['beginTime']
    Eendat = request.POST['endDate']
    EendTime = request.POST['endTime']
    EexpectDate = request.POST['expectDate']
    EexpectTime = request.POST['expectTime']
    Erepeat = request.POST['repeat']
    Elevel = request.POST['level']
    Enature = request.POST['categorie']
    EisSubTodo = request.POST['isSubTodo']
    Edesc=request.POST['desc']
    todos=request.POST['todos'] #小任务
    todos=todos.replace('true','True')
    todos=todos.replace('false','False')
    todos=eval(todos)   #字符串转字典
    if id !='':  # 如果存在修改的id的就对已有的数据进行修改
        eventObject=models.Events.objects.get(id=id)
    else:
        #保存大任务对象
        eventObject=models.Events()
    eventObject.uID=user
    eventObject.Ename=Ename
    eventObject.Estartat=Estartat
    eventObject.EstartTime=EstartTime
    eventObject.Eendat=Eendat
    eventObject.EendTime=EendTime
    if EexpectDate!="":
        eventObject.EexpectDate=EexpectDate
    if EexpectTime!="":
        eventObject.EexpectTime=EexpectTime
    if Erepeat=='false':
        Erepeat=False
    if Erepeat == 'true':
        Erepeat=True
    eventObject.Erepeat=Erepeat
    eventObject.Enature=Enature
    eventObject.Estatus=False
    eventObject.Elevel = Elevel
    if EisSubTodo == 'false':
        EisSubTodo = False
    if EisSubTodo == 'true':
        EisSubTodo = True
    eventObject.EisSubTodo=EisSubTodo
    eventObject.Edesc=Edesc
    eventObject.save()
    #保存小事件对象
    for subtodo in todos:   #保存小事件
        if 'id' in subtodo and subtodo['id'] != '':  # 如果存在修改的id的就对已有的数据进行修改
            subeventObject = models.Events.objects.get(id=subtodo['id'])
        else:
            subeventObject = models.Events()
        subeventObject.uID=user
        subeventObject.Ename = subtodo['title']
        subeventObject.Estartat = subtodo['beginDate']
        subeventObject.EstartTime=subtodo['beginTime']
        subeventObject.Eendat = subtodo['endDate']
        subeventObject.EendTime = subtodo['endTime']
        if 'expectDate' in subtodo and subtodo['expectDate'] !='':
            subeventObject.EexpectDate = subtodo['expectDate']
        if 'expectTime' in subtodo and subtodo['expectTime'] !='':
            eventObject.EexpectTime = subtodo['expectTime']
        subeventObject.Erepeat =subtodo['repeat']
        subeventObject.Enature = subtodo['categorie']
        subeventObject.Estatus = False
        subeventObject.Elevel = subtodo['level']
        subeventObject.EisSubTodo = True
        subeventObject.Edesc=subtodo['desc']
        subeventObject.save()

        #事件关联表
        if 'id' in subtodo:
            if subtodo['id'] =='':
                econtactObj=models.EventsContact()
                econtactObj.Ecid=eventObject
                econtactObj.EDcid=subeventObject
                econtactObj.save()
        else:
            econtactObj = models.EventsContact()
            econtactObj.Ecid = eventObject
            econtactObj.EDcid = subeventObject
            econtactObj.save()

    if 'launchID' in request.POST:
        launchID=request.POST["launchID"]
        launchObject=models.EventsLaunch.objects.get(id=launchID)
        er = models.EventsReceive()
        er.ELid=launchObject
        er.Eventid=eventObject
        er.Receive_at=datetime.datetime.now().strftime('%Y-%m-%d')
        er.save()

    return HttpResponse('保存成功')
    # except:
    #     return HttpResponse('保存失败')

def getEventCards(request):
    date=datetime.datetime.now().strftime('%Y-%m-%d')
    uID=request.POST['uID']
    user = models.Users.objects.get(uID=uID)
    #获取大事件列表
    LargeEventList=models.Events.objects.filter(Q(Estartat__lte=date)&Q(Eendat__gte=date)&Q(EisSubTodo=False)&Q(uID=user))
    for LargeEvent in LargeEventList:
        if LargeEvent.Erepeat:  #判断是否是重复事件，如果是重复事件判断完成日期和当前日期是否相等
            if LargeEvent.EfinishDate==None:    #大事件没有完成
                EcList = models.EventsContact.objects.filter(Ecid=LargeEvent)  # 获取关联表中的小事件
                for Ec in EcList:
                    if Ec.EDcid.Erepeat:  # 小事件重复
                        if Ec.EDcid.EfinishDate:
                            if Ec.EDcid.EfinishDate.strftime('%Y-%m-%d')!=date:
                                Ec.EDcid.Estatus = False
                                Ec.EDcid.save()  # 保存小事件状态
            elif LargeEvent.EfinishDate.strftime('%Y-%m-%d')!=date:    #如果相等将事件状态置为False
                LargeEvent.Estatus=False
                LargeEvent.save()
                EcList=models.EventsContact.objects.filter(Ecid=LargeEvent) #获取关联表中的小事件
                for Ec in EcList:
                    if Ec.EDcid.Erepeat:    #小事件重复
                        Ec.EDcid.Estatus=False
                        Ec.EDcid.save()     #保存小事件状态

    #查找大事件
    data={}
    todoList=[]
    for event in LargeEventList:
        if event.Estatus:
            continue
        task={'id':event.id,'title':event.Ename,'desc':event.Edesc,'level':event.Elevel,'completed':event.Estatus}
        todos=[]
        EcList=models.EventsContact.objects.filter(Q(Ecid=event))  #获取关联事件
        for Ec in EcList:
            event=Ec.EDcid
            if not event.Estatus:
                subTask={'id':event.id,'title':event.Ename,'level':event.Elevel,'endTime':event.EendTime.strftime('%H:%M'),'desc':event.Edesc}
                todos.append(subTask)
        task['todos']=todos
        todoList.append(task)
    data['data']=todoList
    return HttpResponse(json.dumps(data))

def commitSubTask(request):
    idList=request.POST['idList'].split(',')
    largeID=request.POST['largeID']
    if idList!=[""]:
        for id in idList:
            event=models.Events.objects.get(id=id)
            event.EfinishDate=datetime.datetime.now().strftime('%Y-%m-%d')  #事件完成日期
            event.Estatus=True  # 更改小事件的状态
            event.save()
    largeEvent=models.Events.objects.get(id=largeID)
    e_list=models.EventsContact.objects.filter(Q(Ecid=largeEvent))    #获得大事件关联的所有小事件的管理
    all_finished=True
    for e in e_list:
        if e.EDcid.Estatus==False:
            all_finished=False
            break
    if all_finished:
        largeEvent.EfinishDate=datetime.datetime.now().strftime('%Y-%m-%d')  #事件完成日期
        largeEvent.Estatus=True
        largeEvent.save()
    return HttpResponse('提交成功')

#得到任务添加页面的完成和未完成事件
def getEventStatus(request):
    uID=request.POST['uID']
    user=models.Users.objects.get(uID=uID)
    date = datetime.datetime.now().strftime('%Y-%m-%d')
    # 获取大事件列表
    LargeEventList = models.Events.objects.filter(
        Q(Estartat__lte=date) & Q(Eendat__gte=date) & Q(EisSubTodo=False) & Q(uID=user))
    todoUnCompletedList=[]
    todoCompletedList=[]
    for event in LargeEventList:
        if event.Estatus:
            todoCompletedList.append({'id':event.id,'title':event.Ename,'endDate':event.Eendat.strftime('%Y-%m-%d'),'endTime':event.EendTime.strftime('%H:%M'),'categorie':event.Enature,'completed':event.Estatus})
        else:
            todoUnCompletedList.append(
                {'id':event.id,'title': event.Ename, 'endDate': event.Eendat.strftime('%Y-%m-%d'), 'endTime': event.EendTime.strftime('%H:%M'), 'categorie': event.Enature,
                 'completed': event.Estatus})
    data={}
    data['data'] = {'todoUnCompletedList':todoUnCompletedList,'todoCompletedList':todoCompletedList}
    return HttpResponse(json.dumps(data))

def modifyEventDetail(request):
    id=request.POST['id']
    event=models.Events.objects.get(id=id)
    data={}
    data['uID']=event.uID.uID
    data['title']=event.Ename
    data['beginDate']=event.Estartat.strftime('%Y-%m-%d')
    data['beginTime']=event.EstartTime.strftime('%H:%M')
    data['endDate']=event.Eendat.strftime('%Y-%m-%d')
    data['endTime']=event.EendTime.strftime('%H:%M')
    if event.EexpectDate:
        data['expectDate']=event.EexpectDate.strftime('%Y-%m-%d')
    else:
        data['expectDate']=""
    if event.EexpectTime:
        data['expectTime']=event.EexpectTime.strftime('%H:%M')
    else:
        data['expectTime'] =""
    data['repeat']=event.Erepeat
    data['level']=event.Elevel
    data['categorie']=event.Enature
    data['isSubTodo']=event.EisSubTodo
    data['desc']=event.Edesc
    receList=models.EventsReceive.objects.filter(Eventid=event)
    if receList:
        data['isReceive']=1
    else:
        data['isReceive']=0
    todos=[]
    #开始获取小事件
    EcList=models.EventsContact.objects.filter(Ecid=event)
    for Ec in EcList:
        subData = {}
        subData['id']=Ec.EDcid.id
        subData['uID'] = Ec.EDcid.uID.uID
        subData['title'] = Ec.EDcid.Ename
        subData['beginDate'] = Ec.EDcid.Estartat.strftime('%Y-%m-%d')
        subData['beginTime'] = Ec.EDcid.EstartTime.strftime('%H:%M')
        subData['endDate'] = Ec.EDcid.Eendat.strftime('%Y-%m-%d')
        subData['endTime'] = Ec.EDcid.EendTime.strftime('%H:%M')
        if Ec.EDcid.EexpectDate:
            subData['expectDate'] = Ec.EDcid.EexpectDate.strftime('%Y-%m-%d')
        else:
            subData['expectDate'] = ""
        if Ec.EDcid.EexpectTime:
            subData['expectTime'] = Ec.EDcid.EexpectTime.strftime('%H:%M')
        else:
            subData['expectTime'] = ""
        subData['repeat'] = Ec.EDcid.Erepeat
        subData['level'] = Ec.EDcid.Elevel
        subData['categorie'] = Ec.EDcid.Enature
        subData['isSubTodo'] = Ec.EDcid.EisSubTodo
        subData['desc']=Ec.EDcid.Edesc
        todos.append(subData)
    data['todos']=todos
    print(data)
    return HttpResponse(json.dumps(data))

#安卓方式登录
def android_login(request):
    uID = request.POST['uID']
    pwd=request.POST['password']
    userList=models.Users.objects.filter(uID=uID)
    if not userList:
        return HttpResponse(0)
    if pwd==userList[0].pwd:
        data={}
        data['nickName']=userList[0].uName
        return HttpResponse(json.dumps(data))
    return HttpResponse(0)

#根据日历显示任务
def getDateEvents(request):
    date=request.POST['date']
    uID=request.POST['uID']
    user=models.Users.objects.get(uID=uID)
    events=models.Events.objects.filter( Q(Estartat__lte=date) & Q(Eendat__gte=date) & Q(EisSubTodo=False) & Q(uID=user))
    todoUnCompletedList = []
    todoCompletedList = []
    for event in events:
        if event.Estatus:
            todoCompletedList.append(
                {'id': event.id, 'title': event.Ename, 'endDate': event.Eendat.strftime('%Y-%m-%d'),
                 'endTime': event.EendTime.strftime('%H:%M'), 'categorie': event.Enature, 'completed': event.Estatus})
        else:
            todoUnCompletedList.append(
                {'id': event.id, 'title': event.Ename, 'endDate': event.Eendat.strftime('%Y-%m-%d'),
                 'endTime': event.EendTime.strftime('%H:%M'), 'categorie': event.Enature,
                 'completed': event.Estatus})
    data = {}
    data['data'] = {'todoUnCompletedList': todoUnCompletedList, 'todoCompletedList': todoCompletedList}
    return HttpResponse(json.dumps(data))

#删除事件
def deleteEvent(request):
    eID=request.POST['eID']
    uID=request.POST['uID']
    event=models.Events.objects.get(Q(uID__uID=uID)&Q(id=eID))
    EcList=models.EventsContact.objects.filter(Ecid=event)
    if EcList:
        for Ec in EcList:
            Ec.EDcid.delete()
            Ec.Ecid.delete()
            Ec.delete()
    event.delete()
    return HttpResponse()

#提交完成和未完成的事件
def commitEvents(request):
    unIndex=request.POST['unIndex'] #未完成的下标
    index=request.POST['index'] #已完成的下标
    if unIndex:
        unIndex=unIndex.split(',')
        for id in unIndex:
            event=models.Events.objects.get(id=id)
            event.Estatus=True
            event.save()
    if index:
        index = index.split(',')
        for id in index:
            event = models.Events.objects.get(id=id)
            event.Estatus = False
            event.save()
    return HttpResponse()

#修改密码
def modifyPwd(requset):
    uID=requset.POST['uID']
    newPwd=requset.POST['pwd']

    user=models.Users.objects.get(uID=uID)
    user.pwd=newPwd
    user.save()
    return HttpResponse('成功')

#得到分享事件
def getShareEvent(request):
    id = request.POST['id']
    Ename = request.POST['title']
    uID = request.POST['uID']
    user = models.Users.objects.get(uID=uID)
    Estartat = request.POST['beginDate']
    EstartTime = request.POST['beginTime']
    Eendat = request.POST['endDate']
    EendTime = request.POST['endTime']
    EexpectDate = request.POST['expectDate']
    EexpectTime = request.POST['expectTime']
    Erepeat = request.POST['repeat']
    Elevel = request.POST['level']
    Enature = request.POST['categorie']
    EisSubTodo = request.POST['isSubTodo']
    Edesc = request.POST['desc']
    todos = request.POST['todos']  # 小任务
    todos = todos.replace('true', 'True')
    todos = todos.replace('false', 'False')
    todos = eval(todos)  # 字符串转字典
    #获取发送事件
    eLanch = models.EventsLaunch.objects.get(Q(uID__uID=uID) & Q(eName=Ename) & Q(began=Estartat))

    #获取分享的事件
    if id !='':  # 如果存在修改的id的就对已有的数据进行修改
        eventObject=models.Events.objects.get(id=id)
    else:
        #保存大任务对象
        eventObject=models.Events()
    eventObject.uID=user
    eventObject.Ename=Ename
    eventObject.Estartat=Estartat
    eventObject.EstartTime=EstartTime
    eventObject.Eendat=Eendat
    eventObject.EendTime=EendTime
    if EexpectDate!="":
        eventObject.EexpectDate=EexpectDate
    if EexpectTime!="":
        eventObject.EexpectTime=EexpectTime
    if Erepeat=='false':
        Erepeat=False
    if Erepeat == 'true':
        Erepeat=True
    eventObject.Erepeat=Erepeat
    eventObject.Enature=Enature
    eventObject.Estatus=False
    eventObject.Elevel = Elevel
    if EisSubTodo == 'false':
        EisSubTodo = False
    if EisSubTodo == 'true':
        EisSubTodo = True
    eventObject.EisSubTodo=EisSubTodo
    eventObject.Edesc=Edesc
    eventObject.save()
    #保存小事件对象
    for subtodo in todos:   #保存小事件
        if subtodo['id'] != '':  # 如果存在修改的id的就对已有的数据进行修改
            subeventObject = models.Events.objects.get(id=subtodo['id'])
        else:
            subeventObject = models.Events()
        subeventObject.uID=user
        subeventObject.Ename = subtodo['title']
        subeventObject.Estartat = subtodo['beginDate']
        subeventObject.EstartTime=subtodo['beginTime']
        subeventObject.Eendat = subtodo['endDate']
        subeventObject.EendTime = subtodo['endTime']
        if 'expectDate' in subtodo and subtodo['expectDate'] !='':
            subeventObject.EexpectDate = subtodo['expectDate']
        if 'expectTime' in subtodo and subtodo['expectTime'] !='':
            eventObject.EexpectTime = subtodo['expectTime']
        subeventObject.Erepeat =subtodo['repeat']
        subeventObject.Enature = subtodo['categorie']
        subeventObject.Estatus = False
        subeventObject.Elevel = subtodo['level']
        subeventObject.EisSubTodo = True
        subeventObject.Edesc=subtodo['desc']
        subeventObject.save()

        #事件关联表
        econtactObj=models.EventsContact()
        econtactObj.Ecid=eventObject
        econtactObj.EDcid=subeventObject
        econtactObj.save()

    # 创建接收事件
    eRecive = models.EventsReceive()
    eRecive.ELid=eLanch
    eRecive.Eventid=eventObject
    eRecive.Receive_at=datetime.datetime.now().strftime('%Y-%m-%d')
    eRecive.save()
    return HttpResponse('成功')

def getMonitorEvents(request):

    uID=request.POST['uID']
    user=models.Users.objects.get(uID=uID)
    # 查询 EventsLaunch表， 当前用户的所有launchID
    launchIDs=models.EventsLaunch.objects.filter(uID=user)

    # titleList=[]
    # countList=[]
    # completedList=[]
    objList=[]
    for one in launchIDs:   # 在 EventsReceive 表中，查询当前所有 launchID 的事件，如果事件名字为1，把这个删除
        if one.eName=='1':
            continue
        else:   # 不为1，取出eName,遍历所有该launchID对应的事件，判断是否完成，最后得出 完成事件/事件总数*100%
            obj = {}
            obj['title']=one.eName
            # titleList.append(one.eName)
            elist = models.EventsReceive.objects.filter(ELid=one)
            count = len(elist)
            obj['count'] = count
            # countList.append(count)
            obj['date'] = one.Send_at.strftime('%Y-%m-%d')
            completed=0
            for e in elist:
                if e.Eventid.Estatus:   #完成事件
                    completed+=1
                obj['date'] =e.Eventid.Eendat.strftime('%Y-%m-%d')
            obj['completed'] = completed
            if count==0:
                obj['progress']=0
            else:
                obj['progress']=completed*100//count
            # completedList.append(completed)
            objList.append(obj)
    # 返回JSON, 包括题目，两种事件数量(事件比例)
    data={}
    # data['titleList']=titleList
    # data['completedList']=completedList
    # data['countList']=countList
    data['data']=objList
    print(data)
    return  HttpResponse(json.dumps(data))

def setNickName(request):
    uID=request.POST['uID']
    nickName=request.POST['nickName']
    user=models.Users.objects.get(uID=uID)
    user.uName=nickName
    user.save()
    return HttpResponse()
def getNickName(request):
    uID = request.POST['uID']
    user = models.Users.objects.get(uID=uID)
    nickName = user.uName
    data={}
    data['nickName']=nickName
    return HttpResponse(json.dumps(data))
